//
//  YFMenuViewController.m
//  SquashSpark
//
//  Created by Coollang on 2017/10/26.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFMenuViewController.h"
#import "YFMenuViewCell.h"
#import "YFStarVideoController.h"
#import "MyNavigationViewController.h"
#import "YFSportViewController.h"
#import "YFNoticeViewController.h"
#import "UIView+JCDrawTool.h"
#import "JCClubHomeVC.h"
#import "JCMomentsVC.h"
#import "YFSetUpViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImage+YFExtension.h"
#import "YFMMDrawerStateManager.h"

NSString *menuViewCellID = @"YFMenuViewCell";

@interface YFMenuViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSourceArr;
@property (nonatomic, weak) UILabel *nameLabel;
@property (nonatomic, weak) UIImageView *headIconImageview;

@end

@implementation YFMenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    adjustsScrollViewInsets_NO(self.tableView, self);
    [self configuerTableview];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.headIconImageview sd_setImageWithURL:[NSURL URLWithString:[User getUseInfo].icon] placeholderImage:kHeaderPlaceholdImage options:SDWebImageLowPriority| SDWebImageRetryFailed];
    self.nameLabel.text = [[User getUseInfo] nickName];
}

- (void)configuerTableview {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
//    self.tableView.backgroundColor = [UIColor colorWithHex:0x081f35 alpha:0.9];
    [self.tableView registerNib:[UINib nibWithNibName:menuViewCellID bundle:nil] forCellReuseIdentifier:menuViewCellID];
    self.tableView.rowHeight = 55;
    self.tableView.tableHeaderView = [self creatTableViewHead];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, 60)];
    [self.tableView reloadData];
    [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionNone)];
}

- (NSArray *)dataSourceArr {
    if (_dataSourceArr == nil) {
        _dataSourceArr = [YFMenuModel getMenuModels];
    }
    return _dataSourceArr;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YFMenuViewCell *cell = [tableView dequeueReusableCellWithIdentifier:menuViewCellID forIndexPath:indexPath];
    [cell configerMenuViewCellWithModel:self.dataSourceArr[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YFMenuModel *menuModel = self.dataSourceArr[indexPath.row];
    [self didSelectModule:menuModel.menuModuleType];
}

- (void)didSelectModule:(kMenuModuleType)moduleType {
    YFMenuModel *menuModel = nil;
    for (YFMenuModel *model in self.dataSourceArr) {
        if (model.menuModuleType == moduleType) {
            menuModel = model;
            break;
        }
    }
    if (menuModel == nil) {
        return;
    }
    UIViewController *centerVc = [self.centerVcCache objectForKey:menuModel.moduleName];
    switch (moduleType) {
        case kModuleSensor:{
            if (centerVc == nil) {
                MyNavigationViewController *sensorNav = [[UIStoryboard storyboardWithName:@"Sensor" bundle:nil] instantiateInitialViewController];
                centerVc = sensorNav;
                [self.centerVcCache setObject:sensorNav forKey:menuModel.moduleName];
            }
        }
            break;
        case kModuleTraining:{
            centerVc = [self.centerVcCache objectForKey:menuModel.moduleName];
        }
            break;
        case kModuleVideos:{
            if (centerVc == nil) {
                MyNavigationViewController *starVideoNav = [[UIStoryboard storyboardWithName:@"StarVideos" bundle:nil] instantiateInitialViewController];
                centerVc = starVideoNav;
                [self.centerVcCache setObject:starVideoNav forKey:menuModel.moduleName];
            }
        }
            break;
        case kModuleFeeds:{
            // 朋友圈
            if (centerVc == nil) {
                MyNavigationViewController *pyqNav = [[UIStoryboard storyboardWithName:@"Find" bundle:nil] instantiateInitialViewController];
                centerVc = pyqNav;
                
                [self.centerVcCache setObject:pyqNav forKey:menuModel.moduleName];
            }
        }
            break;
        case kModuleClub:{
            //俱乐部
            if (centerVc == nil) {
                MyNavigationViewController *clubNav = [[UIStoryboard storyboardWithName:@"Clubs" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"ClubNavi"];
                centerVc = clubNav;
                [self.centerVcCache setObject:clubNav forKey:menuModel.moduleName];
            }
        }
            break;
        case kModuleNotice:{
            if (centerVc == nil) {
                YFNoticeViewController *noticeVc = [[YFNoticeViewController alloc] initWithNibName:[YFNoticeViewController defalutIndentify] bundle:nil];
                MyNavigationViewController *noticeNav = [[MyNavigationViewController alloc] initWithRootViewController:noticeVc];
                centerVc = noticeNav;
                
                [noticeNav addChildViewController:noticeVc];
                [self.centerVcCache setObject:noticeNav forKey:menuModel.moduleName];
            }
        }
            break;
        case kMoudleSettting:{
            if (centerVc == nil) {
                YFSetUpViewController *setUpVc = [[YFSetUpViewController alloc] init];
                MyNavigationViewController *setUpNav = [[MyNavigationViewController alloc] initWithRootViewController:setUpVc];
                centerVc = setUpNav;
                [self.centerVcCache setObject:setUpVc forKey:[NSString stringWithFormat:@"menuModel.moduleName"]];
            }
        }
            break;
        default:
            break;
    }
    if (centerVc != nil) {
        if ([centerVc isKindOfClass:[UINavigationController class]]) {
            UIViewController *controller = [centerVc childViewControllers].firstObject;
            controller.title = menuModel.moduleName;
            [controller setMenuNavBar];
            MyNavigationViewController *navCenterVc = (MyNavigationViewController *)centerVc;
            navCenterVc.delegate = self;
            // 开启侧滑手势
            centerVc.canLeftOrRightGesOpenMenuView = YES;
            controller.canLeftOrRightGesOpenMenuView = YES;
        }
        [[YFMMDrawerStateManager sharedManager].drawerController setCenterViewController:centerVc withCloseAnimation:YES completion:^(BOOL finished) {
            
        }];
        [[NSNotificationCenter defaultCenter] postNotificationName:kChangeCenterViewControllerNoti
                                                            object:centerVc];
    }
}

#pragma mark - 代理
// 通过代理监测窗口当前展示的控制器
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (viewController.canLeftOrRightGesOpenMenuView) {
        [[YFMMDrawerStateManager sharedManager].drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModePanningNavigationBar |
         MMOpenDrawerGestureModeBezelPanningCenterView];
    }else {
         [[YFMMDrawerStateManager sharedManager].drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    }
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSMutableDictionary<NSString *,UIViewController *> *)centerVcCache {
    if (_centerVcCache == nil) {
        MyNavigationViewController *centerNav = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController];
        YFMenuModel *homeModel = self.dataSourceArr[1];
        NSMutableDictionary *dcit = [NSMutableDictionary dictionaryWithObject:centerNav forKey:homeModel.moduleName];
        _centerVcCache = dcit.mutableCopy;
    }
    return _centerVcCache;
}

- (UIView *)creatTableViewHead {
    UIView *headView = [[UIView alloc] init];
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = kOpenSansFont(OpenSansExtraBold, 22);
    nameLabel.textColor = kTWhiteText;
    nameLabel.text = [[User getUseInfo] nickName];
    self.nameLabel = nameLabel;
    [headView addSubview:nameLabel];
    UIImageView *headIconImg = [UIImageView new];
    self.headIconImageview = headIconImg;
    self.headIconImageview.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showHeadImageTapAction)];
    [self.headIconImageview addGestureRecognizer:tap];
    [headView addSubview:self.headIconImageview];
    
    UIView *lineView = [[UIView alloc] init];
    [headView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(headView);
        make.height.mas_equalTo(6);
    }];
    lineView.backgroundColor = [UIColor colorWithHex:0xffffff alpha:0.1];
    [nameLabel sizeToFit];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lineView.mas_top).offset(-24);
        make.left.equalTo(headView).offset(20);
    }];
    [self.headIconImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nameLabel.mas_top).offset(-18);
        make.left.equalTo(nameLabel);
        make.width.height.mas_equalTo(kAutoHei(82));
    }];
    self.headIconImageview.userInteractionEnabled = YES;
    
    [self.headIconImageview sd_setImageWithURL:[NSURL URLWithString:[User getUseInfo].icon] placeholderImage:kHeaderPlaceholdImage options:SDWebImageLowPriority| SDWebImageRetryFailed];
    headView.backgroundColor = [UIColor clearColor];
    headView.frame = CGRectMake(0, 0, kYFScreenWidth, kAutoHei(230));
    [headIconImg clipsCornerRadius:kAutoHei(41) borderWidth:2 borderColor:kYellowGreenColor];
    return headView;
}

- (void)showHeadImageTapAction {
    YYPhotoGroupItem *headItem = [[YYPhotoGroupItem alloc] init];
    headItem.thumbView = self.headIconImageview;
    headItem.largeImageURL = [NSURL URLWithString:[User getUseInfo].icon];
    headItem.largeImageSize = self.headIconImageview.image.size;
    [UIImage browseURLImages:@[headItem] fromView:self.headIconImageview];
}

@end
